<template>
  <!-- 合同基本信息 -->
  <el-card class="flex1 h0" shadow="hover" header="基本信息" v-loading="loading">
    <el-form ref="basicFormRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="合同名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入合同名称" />
      </el-form-item>
      <el-form-item label="关联客户" prop="customerId">
        <el-select @change="handleChangeRelatedUser" v-model="formData.customerId" placeholder="请输入客户名称" filterable>
          <el-option v-for="item in customerOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="关联房屋" prop="houseId">
        <el-select @change="handleChangeRelatedHouse" v-model="formData.houseId" placeholder="请输入客户名称" filterable>
          <el-option v-for="item in houseOptions" :key="item.id" :label="(item.buildAddress! + ' ' + item.houseAddress)"
            :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="甲方" prop="partyA">
        <el-input v-model="formData.partyA" placeholder="请输入甲方名称" />
      </el-form-item>
      <el-form-item label="乙方" prop="partyB">
        <el-input v-model="formData.partyB" placeholder="请输入乙方名称" />
      </el-form-item>
      <el-form-item label="起始日期" prop="startTime">
        <el-date-picker v-model="formData.startTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择" />
      </el-form-item>
      <el-form-item label="截至日期" prop="endTime">
        <el-date-picker v-model="formData.endTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择" />
      </el-form-item>
      <el-form-item label="总金额" prop="amount">
        <el-input-number v-model="formData.amount" :precision="2" :step="1" :min="0.0" style="width: 180px">
          <template #prefix>
            <span>￥</span>
          </template>
        </el-input-number>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import CustomerAPI, { CustomerPageVO } from "@/api/business/customer/customer.api";
import ContractAPI, { ContractForm, defaultContractForm } from "@/api/flow/contract.api";
import HouseAPI, { HousePageVO } from "@/api/business/customer/house.api";
import { cloneDeep } from "lodash-es";

const props = defineProps<{
  id?: string;
}>();
const emits = defineEmits<{
  (e: "next", key?: string): void;
}>();

const rules = reactive({
  name: [{ required: true, message: "合同名不能为空", trigger: "blur" }],
  customerId: [{ required: true, message: "请选择客户", trigger: "change" }],
  partyA: [{ required: true, message: "甲方不能为空", trigger: "blur" }],
  partyB: [{ required: true, message: "乙方不能为空", trigger: "blur" }],
  amount: [{ required: true, message: "总金额不能为空", trigger: "blur" }],
});

const basicFormRef = ref();
const loading = ref(false);
const customerOptions = ref<CustomerPageVO[]>([]); // 客户下拉数据源
const houseOptions = ref<HousePageVO[]>([]);
const formData = reactive<ContractForm>(cloneDeep(defaultContractForm));

watch(
  () => props.id,
  (nId, oId) => {
    if (nId === oId) return;
    loadContractDetail(nId);
  },
  {
    immediate: true,
    deep: true,
  }
);

onMounted(() => {
  loadAllCustomer();
});

// 加载所有客户
const loadAllCustomer = () => {
  CustomerAPI.getOptions().then((res) => {
    customerOptions.value = res;
  });
};

const loadAllHouse = () => {
  HouseAPI.loadByCustomerId(formData.customerId!).then((res) => {
    houseOptions.value = res;
  });
};

const handleChangeRelatedUser = (id: string) => {
  const cObj = customerOptions.value.find((item) => item.id == id);
  formData.partyA = cObj?.name || "";
  loadAllHouse();
};

const handleChangeRelatedHouse = (id: string) => {
  const cObj = houseOptions.value.find((item) => item.id == id);
  formData.houseName = (cObj?.buildAddress! + cObj?.houseAddress) || "";
};

const clear = () => {
  Object.keys(formData).forEach((k) => {
    formData[k as keyof ContractForm] = null as never;
  });
};

async function loadContractDetail(id?: string) {
  if (!id || id === "0") {
    return;
  }
  await ContractAPI.getFormData(id).then((data) => {
    Object.assign(formData, data);
    // formData.id = id;
    // Object.keys(defaultFormData).forEach((key) => {
    //   formData[key as keyof ContractForm] = data[key as keyof ContractForm] as never;
    // });
  });
}

/**
 * 提交表单
 */
const handleSubmit = () => {
  basicFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      if (formData.id) {
        ContractAPI.update(formData)
          .then(() => {
            ElMessage.success("修改合同成功");
            emits("next");
          })
          .finally(() => (loading.value = false));
      } else {
        ContractAPI.create(formData)
          .then((id) => {
            clear();
            emits("next", id);
          })
          .finally(() => (loading.value = false));
      }
    }
  });
};

defineExpose({
  handleSubmit,
});
</script>

<style scoped>
:deep(.el-card__body) {
  height: calc(100% - 61px);

  .el-scrollbar {
    margin-right: -10px;
    padding-right: 10px;
  }
}

.spus-line {
  margin-bottom: 5px;

  :deep(.el-button) {
    font-size: 0.8rem;
  }

  :deep(span) {
    margin-left: 1;
  }
}
</style>
